package com.feiren.o2o.extjs.datagrid.datasource;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

@Component
public class JdbcDatagridDatasrouce implements DatagridDatasource {

	private Logger logger = LoggerFactory.getLogger(JdbcDatagridDatasrouce.class); 

	
	@Autowired
	private JdbcTemplate jdbcTemplate;

	@SuppressWarnings("deprecation")
	@Override
	public String execute(String id, int start, int end) {
		logger.trace("表格数据源读取表格"+id+"的数据");
		logger.trace("起始行号:"+start);
		logger.trace("结束行号"+end);
		String sql = "select * from (select ROWNUM as rowno," + id + ".* from " + id
				+ " where ROWNUM<=?) where rowno>=?";
		String countSql = "select count(1) from " + id;
		logger.trace("countSql:"+countSql);
		logger.trace("sql:"+sql);
		int count = jdbcTemplate.queryForInt(countSql);
		List<Map<String, Object>> queryResult = jdbcTemplate.queryForList(sql, end, start);
		JSONArray rows = new JSONArray();
		for (Map<String, Object> resultRow : queryResult) {
			JSONObject row = new JSONObject();
			for (String key : resultRow.keySet()) {
				row.put(key, resultRow.get(key));
			}
			rows.put(row);
		}

		JSONObject result = new JSONObject();
		result.put("total", count);
		result.put("data", rows);
		
		Map<String,String> metaData = new HashMap<String,String>();
		metaData.put("root", "data");
		metaData.put("totalProperty", "total");
		result.put("metaData", metaData);
		
		return result.toString();
	}

}
